package com.z.base;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings("serial")
public class BaseAction extends ActionSupport implements Preparable ,ModelDriven<Object>,SessionAware {
	public static final String LOGIN_USER_SESSION_ID="loginUserSessionId";
	protected Map<String, Object> session;
	
	protected final Log logger = LogFactory.getLog(getClass());
	@Override
	public Object getModel() {
		return null;
	}

	@Override
	public void prepare() throws Exception {
	}
	
	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	/**
     * 获取 HttpServletRequest
     * 
     * @return 返回HttpServletRequest
     */
    public HttpServletRequest getRequest() {
        return ServletActionContext.getRequest();
    }

    /**
     * 获取 HttpServletResponse
     * 
     * @return HttpServletResponse
     */
    protected HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

    /**
     * 数据输出
     * 
     * @param text 字符串
     * @param contentType 数据类型
     * @return
     */
    protected String render(String text, String contentType) {
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType(contentType);
            response.getWriter().write(text);
            response.getWriter().flush();
        } catch (IOException e) {
            this.logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 输出字符串数据
     * 
     * @param text
     * @return
     */
    protected String renderText(String text) {
        return render(text, "text/plain;charset=UTF-8");
    }

    /**
     * 输出HTML数据
     * 
     * @param html
     * @return
     */
    protected String renderHtml(String html) {
        return render(html, "text/html;charset=UTF-8");
    }

    /**
     * 输出XML数据
     * 
     * @param xml
     * @return
     */
    protected String renderXML(String xml) {
        return render(xml, "text/xml;charset=UTF-8");
    }
    
    /**
     * 输出XML数据
     * 
     * @param xml
     * @return
     */
    protected String renderJson(String data) {
    	return render(data, "text/x-json;charset=UTF-8");
    }
    
    protected LoginUser getLoginUser() {
    	return (LoginUser) session.get(LOGIN_USER_SESSION_ID);
    }
}
